package com.ittx.dzt.meione.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.business.constant.StoreExtendConstant;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.meione.handler.AbstractMeioneByTimeApiHandler;
import com.ittx.dzt.meione.util.CyUtil;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 售后单增量下载
 * <p>
 * cy.salesOrder.download.byTimeFrame
 * /erp/un/sys/afs/order 商城售后API
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/8/28
 */
@Slf4j
@Service
public class MeioneReturnOrderDownloadByTimeService extends AbstractMeioneByTimeApiHandler<TimeFrameDTO> {

	private static final int DEFAULT_PAGE_SIZE = 100;

	@Autowired
	private MeioneReturnOrderDownloadByIdService meioneReturnOrderDownloadByIdService;


	@Override
	public String getMqTopic() {
		return "不走mq";
	}

	@Override
	public String getMeioneMethod() {
		return "/erp/un/sys/order/v2";
	}

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.RETURNORDER_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	public Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//分发数据,异步下载
		Map<String, Boolean> logMap = new HashMap<>();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);
	}

	@Override
	public Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//探查成功时不返回完整数据,只返回数量
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);
	}

	@Override
	public Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		String orderId = platformApiParamDTO.getPlatformIdentifierTag();
		return this.asyncHandlerById(platformApiParamDTO, orderId);
	}


	/**
	 * sdk
	 * 请求平台接口
	 */
	private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		Map<String, Object> params = new HashMap<>();
		params.put("businessCode", storeConfig.getStoreUniqueCode());
		params.put("updateTimeStart", DateUtil.format(timeFrameDTO.getFrom(), DatePattern.NORM_DATETIME_PATTERN));
		params.put("updateTimeEnd", DateUtil.format(timeFrameDTO.getTo(), DatePattern.NORM_DATETIME_PATTERN));
		params.put("pageSize", DEFAULT_PAGE_SIZE);
		// 状态过滤
		// String status = CyUtil.getStatusStr(platformApiParamDTO, StoreExtendConstant.OrderType.RETURN_TYPE);
		// if (null != status) {
		// 	params.put("afsStatus", status);
		// }

		// 页码从0开始
		long page = 1;
		// 第一次查询，获取总页数
		params.put("pageNo", page);
		Result<?> result = this.executeApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
		if (result.hasError()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
		Map subDataMap = MapUtil.get(dataMap, "subData", Map.class);
		// 订单数量
		Integer total = MapUtil.getInt(subDataMap, "total");
		// 探查模式只返回总数
		if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
			return Result.success().addData(total);
		}
		Integer totalPage = this.totalPage(total, DEFAULT_PAGE_SIZE);
		if (totalPage > 0) {
			// 倒序查询，防止漏单
			for (int i = totalPage; i >= 1; i--) {
				// 页码从0开始
				params.put("pageNo", i);
				result = this.executeApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
				if (result.hasError()) {
					return result;
				}
				dataMap = (Map<String, Object>) resultMap.get("data");
				subDataMap = MapUtil.get(dataMap, "subData", Map.class);
				List<Map> recordsList = MapUtil.get(subDataMap, "records", List.class);
				if (CollUtil.isNotEmpty(recordsList)) {
					// 分发数据到MQ，异步消费下载
					for (Map<String, Object> order : recordsList) {
						String orderId = MapUtil.getStr(order, "orderNo");
						Result sendResult = this.sendRequestToPlatform(platformApiParamDTO, order, true);
						if (sendResult.hasError()) {
							//分发到MQ失败
							logMap.put(orderId, false);
						} else {
							logMap.put(orderId, true);
						}
					}
				}
			}
		}
		return Result.success(logMap);
	}

	/**
	 * sdk
	 * 根据单号查询单条订单信息-- 多线程执行
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String orderId) {
		Result<?> result = meioneReturnOrderDownloadByIdService.getRefundById(platformApiParamDTO, orderId);
		if (result.hasError()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}

	/**
	 * 参数校验
	 *
	 * @param platformApiParamDTO 平台请求参数
	 * @param timeFrameDTO        接口请求参数
	 */
	public Result<?> checkParams(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		if (timeFrameDTO == null || platformApiParamDTO.getStoreConfig() == null ||
				timeFrameDTO.getTo() == null || timeFrameDTO.getFrom() == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0004_MSG, platformApiParamDTO.getRequestId(),
					this.getPlatformCode(), getLocalApiMethod(), timeFrameDTO);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0004, msg));
		}
		return Result.success();
	}


}
